Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
Loading...
Searching...
No Matches
ticker.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2017 Roc authors
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 */
8
9//! @file roc_core/ticker.h
10//! @brief Ticker.
11
12#ifndef ROC_CORE_TICKER_H_
13#define ROC_CORE_TICKER_H_
14
16#include "roc_core/panic.h"
17#include "roc_core/time.h"
18
19namespace roc {
20namespace core {
21
22//! Ticker.
23class Ticker : public NonCopyable<> {
24public:
25 //! Number of ticks.
26 typedef uint64_t Ticks;
27
28 //! Initialize.
29 //! @remarks
30 //! @p freq defines the number of ticks per second.
31 explicit Ticker(Ticks freq)
32 : ratio_(double(freq) / Second)
33 , start_(0)
34 , started_(false) {
35 }
36
37 //! Start ticker.
38 void start() {
39 if (started_) {
40 roc_panic("ticker: can't start ticker twice");
41 }
42 start_ = timestamp();
43 started_ = true;
44 }
45
46 //! Returns number of ticks elapsed since start.
47 //! If ticker is not started yet, it is started automatically.
49 if (!started_) {
50 start();
51 return 0;
52 } else {
53 return Ticks(double(timestamp() - start_) * ratio_);
54 }
55 }
56
57 //! Wait until the given number of ticks elapses since start.
58 //! If ticker is not started yet, it is started automatically.
59 void wait(Ticks ticks) {
60 if (!started_) {
61 start();
62 }
63 sleep_until(start_ + nanoseconds_t(ticks / ratio_));
64 }
65
66private:
67 const double ratio_;
68 nanoseconds_t start_;
69 bool started_;
70};
71
72} // namespace core
73} // namespace roc
74
75#endif // ROC_CORE_TICKER_H_
Base class for non-copyable objects.
Definition: noncopyable.h:23
Ticker.
Definition: ticker.h:23
Ticks elapsed()
Returns number of ticks elapsed since start. If ticker is not started yet, it is started automaticall...
Definition: ticker.h:48
void wait(Ticks ticks)
Wait until the given number of ticks elapses since start. If ticker is not started yet,...
Definition: ticker.h:59
uint64_t Ticks
Number of ticks.
Definition: ticker.h:26
Ticker(Ticks freq)
Initialize.
Definition: ticker.h:31
void start()
Start ticker.
Definition: ticker.h:38
nanoseconds_t timestamp()
Get current timestamp in nanoseconds.
void sleep_until(nanoseconds_t timestamp)
Sleep until the specified absolute time point has been reached.
const nanoseconds_t Second
One second represented in nanoseconds.
Definition: time.h:33
int64_t nanoseconds_t
Nanoseconds.
Definition: time.h:21
Root namespace.
Non-copyable object.
Panic function.
#define roc_panic(...)
Print error message and terminate program gracefully.
Definition: panic.h:42
Time definitions.